package com.guangjian.common.sql;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class CustomerSQL {

	private static Logger log = Logger.getLogger(CustomerSQL.class);

	private static final String config = "sql/sqllist.properties";
	private static final String SQL_FILE_DIR = "sql/";

	private static class PropertiesHolder {

		private static final Map<String, SqlList> sqlListMap = new HashMap<String, SqlList>();
		private static Properties props = null;
		static {
			// 1. 读取配置文件
			try {
				props = new Properties();
				props.load(CustomerSQL.class.getClassLoader().getResourceAsStream(config));

			} catch (Exception e) {
				props = null;
				log.error("Can't read the property file:" + config, e);
			}

			// 2. 读取配置文件中加载的 .sql文件
			if (props != null) {
				String sqlFilePath = null;

				for (Iterator<Object> values = props.values().iterator(); values.hasNext();) {
					sqlFilePath = (String) values.next();

					// 以SQL文件名作为 key
					sqlListMap.put(sqlFilePath.replaceAll(SQL_FILE_DIR, ""), new SqlList(sqlFilePath));
					log.info("sqlList.size()=" + sqlListMap.size());
				}
			}
		}
	}

	public static String getSql(String sqlFile, String sqlId) {

		SqlList sqlList = PropertiesHolder.sqlListMap.get(sqlFile);
		if (sqlList == null) {
			log.error("SQL file '" + sqlFile + "' doesn't exists!");
			return null;
		}

		String sql = sqlList.getSql(sqlId);
		if (StringUtils.isBlank(sql)) {
			log.error("SQL id '" + sqlId + "' doesn't exists in SQL file" + sqlFile + "!");
			return null;
		}

		if (log.isInfoEnabled()) {
			log.info("******************** SQL *******************^");
			log.info("sqlFile = " + sqlFile);
			log.info("sqlId = " + sqlId);
			log.info("sql = " + sql);
			log.info("******************** SQL *******************");
		}
		
		return sql;
	}

	public static void reset(String sqlFileKey) {
		SqlList sqlList = PropertiesHolder.sqlListMap.get(sqlFileKey);
		if (sqlList != null) {
			sqlList.destroy();
			PropertiesHolder.sqlListMap.remove(sqlFileKey);
			log.debug("sqlList.reset(" + sqlFileKey + ")");
			log.debug("sqlList.size()=" + PropertiesHolder.sqlListMap.size());
		}
	}

}
